package com.wenzhoujie.fragment;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDPackageUtil;
import com.wenzhoujie.library.utils.SDResourcesUtil;
import com.wenzhoujie.library.utils.SDToast;
import com.lidroid.xutils.http.ResponseInfo;
import com.lingou.www.R;
import com.nostra13.universalimageloader.cache.disc.BaseDiscCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ta.util.netstate.TANetWorkUtil;
import com.wenzhoujie.AboutUsActivity;
import com.wenzhoujie.ModifyNicknameActivity;
import com.wenzhoujie.ModifyPasswordActivity;
import com.wenzhoujie.MyCaptureActivity;
import com.wenzhoujie.NewsListActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.common.CommonInterface;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.constant.Constant.LoadImageType;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.constant.Constant.canJPush;
import com.wenzhoujie.dao.SettingModelDao;
import com.wenzhoujie.listener.RequestScanResultListener;
import com.wenzhoujie.model.Mobile_qrcodeActModel;
import com.wenzhoujie.model.act.IndexActNewModel;
import com.wenzhoujie.service.AppUpgradeService;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.SDFileUtil;
import com.wenzhoujie.utils.SDHandlerUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 更多fragment
 * 
 * @author js02
 * 
 */
public class MoreFragment extends BaseFragment implements OnClickListener
{

	public static final int REQUEST_CODE_SCAN_CODE = 1;
	
	@ViewInject(id = R.id.frag_my_account_rl_change_nickname)
	private View mRlChangeNickname = null; // 修改nichen
	
	@ViewInject(id = R.id.frag_my_account_rl_change_password)
	private View mRlChangePassword = null; // 修改密码

	@ViewInject(id = R.id.act_more_rl_announcement_list)
	private RelativeLayout mRlAnnouncementList = null;

	@ViewInject(id = R.id.act_more_iv_announcement_list)
	private ImageView mIvAnnouncementList = null;

	@ViewInject(id = R.id.act_more_rl_about_us)
	private RelativeLayout mRlAboutUs = null;

	@ViewInject(id = R.id.act_more_iv_about_us)
	private ImageView mIvAboutUs = null;

	@ViewInject(id = R.id.act_more_tv_about_us)
	private TextView mTvAboutUs = null;

	@ViewInject(id = R.id.act_more_rl_qrcode)
	private RelativeLayout mRlQrcode = null;

	@ViewInject(id = R.id.act_more_rl_clear_cache)
	private RelativeLayout mRlClearCache = null;

	@ViewInject(id = R.id.act_more_tv_cache_size)
	private TextView mTvCacheSize = null;

	@ViewInject(id = R.id.act_more_tv_app_version)
	private TextView mTvAppVersion = null;

	@ViewInject(id = R.id.act_more_rl_upgrade)
	private RelativeLayout mRlUpgrade = null;

	@ViewInject(id = R.id.act_more_tv_load_image_cb_mobile_net_subtitle)
	//private CheckBox mCbLoadImageInMobileNet = null;
	private Switch mCbLoadImageInMobileNet = null;

	@ViewInject(id = R.id.act_more_cb_jpush)
	private Switch mJpushSwitch = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_more, container, false);
		//view = setmTitleType(TitleType.TITLE_SIMPLE, view);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		//initTitle();
		bindData();
		showCacheSize();
		registeClick();

	}

	private void initTitle()
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				// TODO Auto-generated method stub

			}
		});
		mTitleSimple.setLeftLayoutVisibility(View.GONE);
		mTitleSimple.setTitleTop("更多");
	}

	private void bindData()
	{
		int loadImageInMobileNet = SettingModelDao.getLoadImageType();
		if (loadImageInMobileNet == LoadImageType.ALL)
		{
			mCbLoadImageInMobileNet.setChecked(true);
			//mCbLoadImageInMobileNet.setText("是");
		} else
		{
			mCbLoadImageInMobileNet.setChecked(false);
			//mCbLoadImageInMobileNet.setText("否");
		}
		mCbLoadImageInMobileNet.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{

				if (isChecked)
				{
					SettingModelDao.getInstance().updateLoadImageType(LoadImageType.ALL);
					//mCbLoadImageInMobileNet.setText("是");
				} else
				{
					SettingModelDao.getInstance().updateLoadImageType(LoadImageType.ONLY_WIFI);
					//mCbLoadImageInMobileNet.setText("否");
				}
				App.getApplication().onConnect(TANetWorkUtil.getAPNType(App.getApplication()));
			}
		});

		//////////////
		int isAllowJpush = SettingModelDao.getInstance().canPushMessage();
		if (isAllowJpush == canJPush.YES)
		{
			mJpushSwitch.setChecked(true);
			//mCbLoadImageInMobileNet.setText("是");
		} else
		{
			mJpushSwitch.setChecked(false);
			//mCbLoadImageInMobileNet.setText("否");
		}
		mJpushSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{

				if (isChecked)
				{
					SettingModelDao.getInstance().updateCanPushMessage(canJPush.YES);
					//mCbLoadImageInMobileNet.setText("是");
				} else
				{
					SettingModelDao.getInstance().updateCanPushMessage(canJPush.NO);
					//mCbLoadImageInMobileNet.setText("否");
				}
				App.getApplication().onConnect(TANetWorkUtil.getAPNType(App.getApplication()));
			}
		});

		/////////////
		PackageInfo pi = SDPackageUtil.getCurrentPackageInfo();
		mTvAppVersion.setText(String.valueOf(pi.versionName));
	}

	private void showCacheSize()
	{
		BaseDiscCache baseDisc = (BaseDiscCache) ImageLoader.getInstance().getDiscCache();

		if (baseDisc != null)
		{
			long cacheSize = SDFileUtil.getFileSize(baseDisc.getCacheDir());
			mTvCacheSize.setText(SDFileUtil.formetFileSize(cacheSize));
		}
	}

	private void registeClick()
	{
		mRlChangeNickname.setOnClickListener(this);
		mRlChangePassword.setOnClickListener(this);
		mRlAnnouncementList.setOnClickListener(this);
		mRlAboutUs.setOnClickListener(this);
		mRlQrcode.setOnClickListener(this);
		mRlClearCache.setOnClickListener(this);
		mRlUpgrade.setOnClickListener(this);
		mRlUpgrade.setOnLongClickListener(new OnLongClickListener()
		{
			@Override
			public boolean onLongClick(View v)
			{
				PackageInfo pi = SDPackageUtil.getCurrentPackageInfo();
				StringBuilder sb = new StringBuilder();
				sb.append("appName=" + SDResourcesUtil.getString(R.string.app_name) + "\r\n");
				sb.append("package=" + pi.packageName + "\r\n");
				sb.append("versionCode=" + pi.versionCode + "\r\n");
				sb.append("versionName=" + pi.versionName + "\r\n");
				sb.append("serverUrl=" + ApkConstant.SERVER_API_URL_MID + "\r\n");
				sb.append("jpushKey=" + SDResourcesUtil.getString(R.string.jpush_key) + "\r\n");
				sb.append("umengKey=" + SDResourcesUtil.getString(R.string.umeng_key) + "\r\n");
				sb.append("baiduKey=" + SDResourcesUtil.getString(R.string.baidu_key) + "\r\n");
				new SDDialogConfirm().setTextContent(sb.toString()).show();
				return false;
			}
		});
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_more_rl_announcement_list:
			clickAnnoucement();
			break;
		case R.id.act_more_rl_about_us:
			clickAbout();
			break;
		case R.id.act_more_rl_qrcode:
			clickQrcode();
			break;
		case R.id.act_more_rl_clear_cache:
			clickClearCache();
			break;
		case R.id.act_more_rl_upgrade:
			clickTestUpgrade();
			break;
		case R.id.frag_my_account_rl_change_password:
			clickChangePassword();// 修改密码
			break;
		case R.id.frag_my_account_rl_change_nickname:
			clickChangeNickname();// 修改
			break;	
		default:
			break;
		}
	}
	
	private void clickChangeNickname()
	{
		startActivity(new Intent(getActivity(), ModifyNicknameActivity.class));
	}
	
	private void clickChangePassword()
	{
		startActivity(new Intent(getActivity(), ModifyPasswordActivity.class));
	}
	/**
	 * 扫一扫
	 */
	private void clickQrcode()
	{
		Intent intent = new Intent(App.getApplication(), MyCaptureActivity.class);
		startActivityForResult(intent, REQUEST_CODE_SCAN_CODE);
	}

	/**
	 * 关于
	 */
	private void clickAbout()
	{
		Intent intent = new Intent(getActivity(), AboutUsActivity.class);
		startActivity(intent);
	}

	/**
	 * 公告列表
	 */
	private void clickAnnoucement()
	{
		startActivity(new Intent(App.getApplication(), NewsListActivity.class));
	}

	private void clickTestUpgrade()
	{
		Intent intent = new Intent(App.getApplication(), AppUpgradeService.class);
		intent.putExtra(AppUpgradeService.EXTRA_SERVICE_START_TYPE, 1);
		getActivity().startService(intent);
	}

	/**
	 * 清除缓存
	 */
	private void clickClearCache()
	{
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				ImageLoader.getInstance().clearDiscCache();
				SDHandlerUtil.runOnUiThread(new Runnable()
				{
					public void run()
					{
						mTvCacheSize.setText("0.00B");
						SDToast.showToast("清除完毕");
					}
				});
			}
		}).start();
	}

	@Override
	public void onHiddenChanged(boolean hidden)
	{
		if (!hidden)
		{
			showCacheSize();
		}
		super.onHiddenChanged(hidden);
	}

	/**
	 * 处理扫描结果
	 * 
	 * @param scanResult
	 */
	private void requestScanResult(String scanResult)
	{
		if (AppHelper.isEmptyString(scanResult))
		{
			SDToast.showToast("扫描结果为空");
			return;
		}

		CommonInterface.requestScanResult(scanResult, new RequestScanResultListener()
		{
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo, Mobile_qrcodeActModel model)
			{
				int type = model.getTypeFormat();
				if (type == 0) // 未解释成功
				{
					SDToast.showToast("对不起，解释二维码失败");
				} else
				{
					Intent intent = IndexActNewModel.createIntentByType(type, model.getData(), false);
					if (intent != null)
					{
						try
						{
							startActivity(intent);
						} catch (Exception e)
						{
							e.printStackTrace();
						}
					} else
					{
						SDToast.showToast("未知的类型：" + type);
					}
				}
			}

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("正在解释验证码");
			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
			}

			@Override
			public void onFailure()
			{
				SDToast.showToast("解释失败");
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case REQUEST_CODE_SCAN_CODE:
			if (resultCode == MyCaptureActivity.RESULT_CODE_SCAN_SUCCESS)
			{
				String scanResult = data.getStringExtra(MyCaptureActivity.EXTRA_RESULT_SUCCESS_STRING);
				requestScanResult(scanResult);
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}